<template>
  <Modal
    v-model="showModal"
    :title="optObj.title"
    width="60%"
    :footer-hide="true"
    :mask-closable="false"
    :closable="false">
    <div class="form_box">
      <Form
        ref="formValidate"
        :model="formValidate"
        :rules="ruleValidate"
        :label-width="100"
        label-position="left">
        <FormItem label="案场状态：">
          <span>{{ optObj.tabText }}</span>
        </FormItem>

        <FormItem label="配置项：">
          <Select v-model="formValidate.configType" :disabled="editFlag">
            <Option :value="1">案场内客户到访跟进保护期</Option>
            <Option :value="2">案场客户流出保护期</Option>
          </Select>
        </FormItem>
        <FormItem label="公司范围：" prop="companyId" v-if="showModal">
          <tree_select
            v-model="formValidate.companyId"
            ref="areaTree"
            :treeList="companyList"
            selectPlaceholder="请选择"
            :maxTagCount="3"
            :saveParent="true"
            @openTree="treeSelectHandle"></tree_select>
        </FormItem>

        <FormItem label="状态：">
          <div class="protect_date">
            <i-switch v-model="formValidate.protectDate" />
            <div style="margin-left: 16px" v-if="formValidate.protectDate && formValidate.configType == 1">
              <span>到访后，连续</span>
              <InputNumber
                :min="0"
                v-model="formValidate.days"
                :precision="0"
                type="number"
                style="width: 48px" />
              <span>天不跟进，客户将进入案场公客池</span>
            </div>
            <div style="margin-left: 16px" v-if="formValidate.protectDate && formValidate.configType == 2">
              <span>案场公客池内客户停留</span>
              <InputNumber
                :min="0"
                v-model="formValidate.days"
                :precision="0"
                type="number"
                style="width: 48px" />
              <span>天后，客户将流入公司客户池</span>
            </div>
            <div><Input style="opacity: 0; width: 0"></Input></div>
          </div>
        </FormItem>
        <FormItem label="同步至：">
          <RadioGroup v-model="formValidate.case" type="button">
            <Radio :label="1">全部案场</Radio>
            <Radio :label="0">标准案场（“自定义规则案场”不会同步）</Radio>
          </RadioGroup>
        </FormItem>
      </Form>
      <div class="btn_box">
        <Button type="primary" @click="ok">确定</Button>
        <Button style="margin-right: 24px" @click="cancel">取消</Button>
      </div>
    </div>
  </Modal>
</template>

<script>
  import tree_select from '@/components/tree_select.vue'
  import processApi from '@/biz/flowApproval/processManagement'
  import protectOption from '@/biz/protectOption/protectOption'

  export default {
    name: 'DtManagementEditModal',
    props: {},
    components: {
      tree_select
    },

    data() {
      return {
        optObj: {
          title: '新增',
          tabText: '案前',
          tabVal: '1'
        },
        ruleValidate: {
          companyId: [
            {
              required: true,
              type: 'array',
              message: '请选择公司范围',
              trigger: 'blur,change'
            }
          ]
        },
        showModal: false,
        formValidate: {
          configType: 1,
          companyId: [],
          protectDate: false,
          days: null,
          case: 0,
          id: null
        },
        companyList: [],
        errMsg: '',
        count: 0,
        oldArr: [],
        editFlag: true
      }
    },

    mounted() {
      this.getBusinessList()
    },

    methods: {
      //获取业务组织架构
      getBusinessList(data) {
        processApi.getBusinessOrganTree().then((res) => {
          if (data) {
            let companyIdTmp = data.companyId.split(',')
            res &&
              res.forEach((item) => {
                if (companyIdTmp && companyIdTmp.includes(String(item.id))) {
                  item.checked = true
                }
                item.children.forEach((itemC) => {
                  if (companyIdTmp && companyIdTmp.includes(String(itemC.id))) {
                    itemC.checked = true
                  }
                  itemC.children.forEach((itemL) => {
                    if (companyIdTmp && companyIdTmp.includes(String(itemL.id))) {
                      itemL.checked = true
                    }
                  })
                })
              })
          }
          this.companyList = res
        })
      },
      // 选择组织后
      treeSelectHandle(val) {
        let newArr = [...val].filter((item) => {
          return !this.oldArr.includes(item)
        })
        this.count++
        if (this.count === 1) return
        if (val?.length > 0) {
          let params = {
            buildingStatus: Number(this.optObj.tabVal),
            orgIds: newArr,
            configType: this.formValidate.configType
          }
          protectOption.haveOrg(params).then((res) => {
            if (res) {
              this.errMsg = `${res}已创建过`
              return this.$Message.error(this.errMsg)
            } else {
              this.errMsg = ''
            }
          })
        }
      },
      show(obj1, obj2) {
        if (obj1.title == '编辑') {
          this.editFlag = true
        } else {
          this.editFlag = false
        }

        console.log(obj1, obj2, 'vvv')
        this.optObj = Object.assign({}, obj1)
        if (obj2) {
          console.log(obj2)
          this.$nextTick(async () => {
            await this.getBusinessList({ companyId: obj1.companyId })
            this.formValidate = Object.assign({}, obj2)
          })
          this.oldArr = [...obj2.companyId]
        }
        this.showModal = true
      },
      // 重置 关闭弹窗
      cancel() {
        console.log('111')
        this.getBusinessList()
        this.formValidate.configType = 1
        this.formValidate.protectDate = false
        this.formValidate.days = null
        this.formValidate.companyId = []
        this.formValidate.case = 0
        this.count = 0
        this.errMsg = ''
        this.showModal = false
      },
      ok() {
        this.$refs.formValidate.validate((valid) => {
          if (valid) {
            if (this.errMsg) {
              return this.$Message.error(this.errMsg)
            }
            if (
              this.formValidate.protectDate &&
              ((this.formValidate.configType == 2 && this.formValidate.days === '') ||
                (this.formValidate.configType == 1 && this.formValidate.days < 1))
            ) {
              this.$Message.error('请填写保护期天数')
              return
            }

            if (this.optObj.title === '新增') {
              this.addFun()
            } else {
              this.editFun()
            }
          }
        })
      },
      // 新增接口
      addFun() {
        let params1 = {
          buildingStatus: Number(this.optObj.tabVal),
          orgIds: this.formValidate.companyId,
          configType: this.formValidate.configType
        }
        protectOption.haveOrg(params1).then((res) => {
          if (res) {
            this.errMsg = `${res}已创建过`
            return this.$Message.error(this.errMsg)
          } else {
            let params = {
              buildingStatus: Number(this.optObj.tabVal),
              configDays: this.formValidate.protectDate ? this.formValidate.days : null,
              configStatus: this.formValidate.protectDate ? 1 : 0,
              orgIds: this.formValidate.companyId,
              synchronizeStatus: this.formValidate.case,
              configType: this.formValidate.configType
            }
            protectOption.addOrgProtect(params).then((res) => {
              this.$Message.success('新增成功')
              this.cancel()
              this.$emit('getAgain')
            })
          }
        })
      },
      // 编辑接口
      editFun() {
        let params = {
          buildingStatus: Number(this.optObj.tabVal),
          configDays: this.formValidate.protectDate ? this.formValidate.days : null,
          configStatus: this.formValidate.protectDate ? 1 : 0,
          orgIds: this.formValidate.companyId,
          synchronizeStatus: this.formValidate.case,
          id: this.formValidate.id,
          configType: this.formValidate.configType
        }
        protectOption.editOrgProtect(params).then((res) => {
          this.$Message.success('修改成功')
          this.cancel()
          this.$emit('getAgain')
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
  .protect_date {
    display: flex;
    align-items: center;
    height: 100%;
  }
  .btn_box {
    display: flex;
    flex-direction: row-reverse;
    padding-right: 24px;
  }
</style>
